package com.psbc.online_xdclass.controller;

import com.psbc.online_xdclass.model.entity.User;
import com.psbc.online_xdclass.model.request.LoginRequest;
import com.psbc.online_xdclass.service.UserService;
import com.psbc.online_xdclass.utils.JsonData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@RestController
@RequestMapping("/api/v1/pri/user")
public class UserController {
    @Autowired
    private UserService userService;

    /**
     *添加用户，唯一性就是那个phone是唯一索引，通过phone来区分用户
     * @param userInfo
     * @return
     */
    @PostMapping("/register")
    public JsonData register(@RequestBody Map<String,String> userInfo){
       int rows = userService.save(userInfo);
       return rows == 1 ? JsonData.buildSuccess() : JsonData.buildError("注册失败，请重试");
    }

    /**
     * 登录接口
     * @param loginRequest
     * @return
     */
    @PostMapping("/login")
    public JsonData login(@RequestBody LoginRequest loginRequest){
        String token = userService.findByPhoneAndPwd(loginRequest.getPhone(),loginRequest.getPwd());
        return token ==null ? JsonData.buildError("登录错误，请重新登录") : JsonData.buildSuccess(token);
    }

    /**
     * 根据用户id查询用户信息
     * @param request
     * @return
     */
    @RequestMapping("/find_by_token")
    public JsonData findUserInfoByToken(HttpServletRequest request){
        Integer userId = (Integer) request.getAttribute("user_id");
        if (userId == null){
            return JsonData.buildError("用户查询失败");
        }
        User user = userService.findUserById(userId);
        return JsonData.buildSuccess(user);
    }
}
